<template>
    <div id="bg" class="w-h-100" style="box-sizing: border-box; overflow: hidden">
        <div class="w-h-100 ver-flex">
            <el-card class="box-card" shadow="never" :body-style="{ paddingBottom: '0' }">
                <search ref="searchRef" v-bind="regulationSearch">
                    <template #footer="scope">
                        <el-button type="primary" icon="ele-Search" @click="query"> {{ $t('qEh3zD5bC8bZb4bLvFe29') }}
                        </el-button>
                        <el-button icon="ele-Plus" type="primary" @click="add"> {{ $t('wnpevud10fwvwhDyynC4A') }}
                        </el-button>
                        <el-button icon="ele-Download" type="primary" @click="down"> {{ $t('tjpsapuRnb7E4MDf9i9') }}
                        </el-button>
                        <el-upload action="action" :limit="1" :show-file-list="false" accept=".xlsx"
                            :http-request="uploadFile1" style="margin-left: 10px; padding-top: 4px">
                            <template #trigger>
                                <el-button icon="ele-Upload" type="primary">{{ $t('v5eJ3w4xVv87pHzef9Ijh') }}</el-button>
                            </template>
                        </el-upload>
                    </template>
                </search>
            </el-card>

            <el-card class="w-h-100 flex-1 box-card" style="margin-top: 16px" shadow="never"
                :body-style="{ paddingBottom: '0' }">
                <inscroll-table :data-list="list" v-bind="regulationTableConfig" :dataCount="Number(totalRows)"
                    :handle-size-change="handleSizeChange" :handle-current-change="handleCurrentChange">
                    <template #fileCount="scope">
                        <div>
                            {{ scope.row.v_FilePath ? scope.row.v_FilePath.length : 0 }}
                        </div>
                    </template>

                    <template #operation="scope">
                        <div>
                            <!-- <el-button icon="ele-Document" @click="() => {
                                    detailAction(scope.row);
                                }
                                " type="primary" size="small" text>
                                {{ $t('ucC9qxHvkvdh9OGEo1pn') }}
                            </el-button> -->
                            <el-button icon="ele-Edit" @click="() => {
                                changeAction(scope.row);
                            }
                                " type="primary" size="small" text>
                                {{ $t('kiUkiqa3h0HLymgh7eEb') }}
                            </el-button>
                            <el-button icon="ele-Delete" @click="() => {
                                deleteAction(scope.row);
                            }
                                " type="danger" size="small" text>
                                {{ $t('mkwlMbm3qr88f0XxV9Pje') }}
                            </el-button>
                            <el-button size="small" @click="documentClick(scope.row)" text type="primary"> 上传文件 </el-button>
                        </div>
                    </template>
                </inscroll-table>
            </el-card>
        </div>
        <regulation-form ref="formRef" @submit="(param: any) => submitHandle(param)"></regulation-form>
    </div>
    <!-- 文件 -->
    <uploadFile isAccept="" :fileInfo="fileInfo" :isUseDialog="fileDialog" @cancelFileClick="cancelFileClick"
        @controlFileClick="controlFileClick" @updateData="getData" />
</template>

<script lang="ts" setup>
import { inscrollTable, regulationTableConfig } from './config/table/index';
import { search, regulationSearch } from './config/search/index';
import { ref } from 'vue';
import getStaticTableData from '/@/utils/staticGetTableData';
import { getRegulationList, postRegulation, postChangeRegulation, postDeleteRegulation } from '/@/api/safety-play/index';

import uploadFile from "./component/uploadFile.vue"
import regulationForm from './component/add-edit-laws-regulation.vue';
import { IPostRegulationType } from '/@/types/ys/index';
import { ElMessageBox } from 'element-plus';
import { fileToBase64, downUrl } from '/@/utils/hook/index';
import { postExcel } from '/@/api/safety-play/discernAPI';

import commonRequest from '/@/api/common/common';
import eventBus from '/@/utils/eventBus';
import { uploadFiles } from '/@/utils/hook/index';

import useCurrentInstance from '/@/utils/hook/useCurrentInstance';
const { proxy } = useCurrentInstance();
const $t = proxy.$t;

const formRef = ref();
const { list, totalRows, handleSizeChange, handleCurrentChange, getData } = getStaticTableData(getRegulationList, {}, regulationSearch.searchObj);
//附件删除后刷新列表
eventBus.on('getData', getData);
let isChange = false;
let currentSelectData: any;

const down = () => {
    downUrl(window.$host + '/Upload/SMS/Batch/LegalCode.xlsx');
};

const uploadFile1 = (params: any) => {
    fileToBase64(params.file)
        .then(async (base64) => {
            console.log(base64); // 输出文件的Base64编码
            await postExcel({ ModelType: 'LegalCode', FileContent: base64 });
            getData();
        })
        .catch((error) => {
            console.error(error); // 输出错误信息
        });
};

const add = () => {
    isChange = false;
    formRef.value.addNew({});
};
const changeAction = (data: any) => {
    currentSelectData = data;
    isChange = true;
    formRef.value.change(data);
};
// const detailAction = (data: any) => {
//     formRef.value.detail(data);
// };

const query = () => {
    getData();
};
const deleteAction = (data: any) => {
    ElMessageBox.confirm($t('itYcbTIj20MmWuPdBMgvd'), $t('nHdM3UcfLoZbHyqgSa3cx'), {
        confirmButtonText: $t('cpmrq09Mw3tfVmwWGsZzb'),
        cancelButtonText: $t('wFa44E4Iz025Ha2gYeDop'),
        type: 'warning',
        center: true,
    })
        .then(async () => {
            await postDeleteRegulation({
                n_Id: data.n_Id,
            });
            getData();
        })
        .catch(() => { });
};
//提交
const submitHandle = async (param: any) => {
    let postFileID = 0;
    //新增时获取雪花id为filedId赋值
    // if (!isChange) {
    // 	let res = await commonRequest.getGenerateId();
    // 	tempFileID = res.data;
    // }
    // if (isChange) {
    // 	console.log('is桢');
    // } else {
    // 	console.log('is假');
    // }
    let res = await commonRequest.getGenerateId();
    postFileID = res.data; //雪花id

    let postData: IPostRegulationType = {
        V_LegalName: param.v_LegalName,
        V_StandardCode: param.v_StandardCode,
        D_PublicationDate: param.d_PublicationDate,
        D_EffectiveDate: param.d_EffectiveDate,
        V_ScopeApplication: param.v_ScopeApplication,
        V_Remake: param.v_Remake,
        N_LegalTypeId: isChange && currentSelectData.v_LegalTypeName == param.n_LegalTypeId ? currentSelectData.n_LegalTypeId : param.n_LegalTypeId,
        N_DocumentId: postFileID,
    };
    if (formRef.value.fileList.length > 0) {
        await uploadFiles(postFileID, formRef.value.fileList);
    }
    if (isChange) {
        postData.n_Id = currentSelectData.n_Id;
        await postChangeRegulation(postData);
    } else {
        await postRegulation(postData);
    }
    getData();
};

/*** 附件管理 */
const fileInfo = ref();
const fileDialog = ref(false);
/*** cancelFileClick 文件上传取消事件 */
const cancelFileClick = () => {
    fileDialog.value = false;
};

/*** controlFileClick 文件上传提交事件 */
const controlFileClick = () => {
    fileDialog.value = false;
}

/*** documentClick 文档上传事件 */
const documentClick = (val: any) => {
    console.log(val, 'val')
    val.sourceType = 10;
    val.sourceId = val.n_Id;
    val.titleCon = '上传制度文档';
    fileInfo.value = JSON.stringify(val);
    fileDialog.value = true;
}

</script>

<!-- scoped属性使style有自己独立的作用域(属性选择器实现 title[data-v-xxx]) -->
<style lang="scss" scoped>
#bg {
    :deep(.el-card__body) {
        height: 100%;
    }

    ::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell {
        background: none;
    }
}
</style>
